<template>
  <div class="orderMall page" ref="webview">
    <div class="hd-bar">
      <van-nav-bar title="我的订单" class="bg_white" left-arrow @click-left="$router.push({'path': '/my'})"></van-nav-bar>
      <div class="order-tab">
        <template v-for="(item,index) in orderTab">
          <div class="tab" :key="index" :class="{active: orderTabIndex === item.state}">
            <span class="name" ref="orderTab" @click="orderTabchange(index)">{{item.name}}</span>
          </div>
        </template>
        <span class="activeLine" v-if="orderTabLeft" :style="'left:'+orderTabLeft+'px;width:'+orderTabWidth+'px'"></span>
      </div>
    </div>
    <div class="content">
      <div class="webview">
        <van-pull-refresh v-model="isLoading" @refresh="onRefresh" style="height:100%;">
          <van-empty description="暂无订单" image="/static/img/empty-image-default.png" v-if="dataList.length===0" />
          <van-list v-model="loading" :finished="finished" :finished-text="dataList.length>2?'没有更多了':''" @load="onLoad"
            :offset="50" :immediate-check="false" v-else>
            <template v-for="(item, index) in dataList">
              <div class="order-list" @click="goDetailsLink(item.id)" :key="'order-item-'+ index">
                <div class="title">
                  <span class="stroe">{{item.shop_name}}</span>
                  <span class="state" v-if="item.order_status === 0">待发货</span>
                  <span class="state" v-if="item.order_status === 1">待收货</span>
                  <span class="state" v-if="item.order_status === 2">已收货</span>
                  <span class="state" v-if="item.order_status === -1">已取消</span>
                  <span class="state" v-if="item.order_status === -2">未付款</span>
                  <span class="state" v-if="item.order_status === -3">会员拒收</span>
                  <span class="state" v-if="item.order_status === -4">系统自动取消</span>
                </div>
                <div class="info-box">
                  <div class="images">
                    <template v-for="(res,index) in item.goodsList">
                      <div class="img" :key="index">
                        <van-image width="100%" :height="$tools.toPX(160)" fit="contain" lazy-load :src="res.goods_img">
                          <template v-slot:loading>
                            <van-loading type="spinner" size="24" />
                          </template>
                        </van-image>
                      </div>
                    </template>
                  </div>
                  <div class="slot">
                    <div class="m-num">
                      <div class="m-price">{{item.total_money}}</div>
                      <span class="num">共{{item.cnt}}件</span>
                    </div>
                  </div>
                </div>
                <div class="operation" v-if="item.order_status === -2 || item.order_status === 2 || item.order_status === 1">
                  <!-- <div class="tracking">
                  <template v-if="item.logistics_no">快递单号:
                    <span class="text">{{item.logistics_no}}</span>
                    <span class="icon-copy" @click.stop="copy(item.logistics_no)"></span>
                  </template>
                </div> -->

                  <span class="cancel" v-if="item.order_status === -2" @click.stop="cancelGoods(item)">取消订单</span>
                  <span class="buy" v-if="item.order_status === 2" @click.stop="buyGoods(item)">再次购买</span>
                  <span class="pay" v-if="item.order_status === -2" @click.stop="payGoods(item)">付款
                    <van-count-down class="time" :time="item.payEndTime" @finish="countDownFinish" format="mm:ss" />
                  </span>
                  <span class="cancel" v-if="item.order_status === 1" @click.stop="confirmGoods(item)">确认收货</span>
                </div>
              </div>
            </template>
          </van-list>
        </van-pull-refresh>
      </div>
    </div>
    <van-popup v-model="isPopupShow" round position="bottom">
      <div class="confirm-goods">
        <div class="title_name">确认收货</div>
        <div class="confirm_info">您是否确认已经收到以下订单的商品？</div>
        <div class="info-box">
          <div class="img">
            <van-image width="100%" :height="$tools.toPX(160)" fit="contain" lazy-load :src="orderInfo.goods_img">
              <template v-slot:loading>
                <van-loading type="spinner" size="24" />
              </template>
            </van-image>
          </div>
          <div class="info">
            <p class="name van-multi-ellipsis--l2">{{orderInfo.goods_name}}</p>
            <div class="slot">
              <span class="c1">{{orderInfo.norm_price}}</span>
              <span class="c2">x{{orderInfo.num}}</span>
            </div>
          </div>
        </div>
        <div class="tis">谨慎操作，如尚未收到商品，请不要点击确认！</div>
        <div class="submit">
          <span class="btn cancel" @click="isPopupShow= false">取消操作</span>
          <span class="btn confirm" @click="confirmrRecv">
            <template v-if="isLoading">
              <van-loading color="#1989fa" />
            </template>
            <template v-else>
              确认收货
            </template>
          </span>
        </div>
      </div>
    </van-popup>
    <van-popup v-model="isPopupPay" @click-overlay="closePayPopup" round position="bottom" style="overflow-y: unset;">
      <pay-mod v-model="isPopupPayLoading" @change="changeOrderPay" />
    </van-popup>
  </div>
</template>
<script>
import mixins from '@/utils/mixins';
export default {
  name: 'orderMall',
  data() {
    return {
      orderTabIndex: 0,
      orderTabLeft: 0,
      orderTabWidth: 0,
      isPopupPayLoading: false,
      isPopupPay: false,
      isLoading: false,
      isPopupShow: false,
      apiType: 'user',
      apiUrl: 'order',
      paramsUrl: 'list',
      orderInfo: {},
      params: {
        ca: 2
      },
      orderTab: [
        {
          state: 0,
          name: '全部'
        },
        {
          state: 1,
          name: '待付款'
        },
        {
          state: 2,
          name: '待收货'
        },
        {
          state: 3,
          name: '已完成'
        },
        {
          state: 4,
          name: '已取消'
        }
      ]
    };
  },
  mixins: [mixins],

  mounted() {
    this.$nextTick(() => {
      // this.setStatus(this.orderTabIndex);
      var status = parseInt(localStorage.getItem('orderStatus'));
      this.orderTabchange(status);
    });
  },
  destroyed() {
    // localStorage.removeItem('orderStatus');
  },
  methods: {
    closePayPopup() {
      this.isPopupPay = false;
      this.isLoading = false;
    },
    // 去支付
    changeOrderPay(type) {
      this.OrderPay(type);
    },
    // 拉起支付APP
    OrderPay(payMethod) {
      this.isPopupPayLoading = true;
      var options = {
        orderNo: this.orderNo,
        payMethod
      };
      this.$API.order.pay(options).then(res => {
        if (!res.code) {
          if (window.api) {
            this.getOrder(res.data);
          } else {
            this.$toast('目前只支持APP里支付');
            this.isPopupPayLoading = false;
          }
        }
      });
    },
    // 拉起微信客户端
    getOrder(data) {
      var wxPay = window.api.require('wxPayPlus');
      wxPay.payOrder(
        {
          apiKey: data.appId,
          orderId: data.prepayId,
          mchId: data.mchId || '1533095261',
          nonceStr: data.nonceStr,
          timeStamp: data.timeStamp,
          package: data.packageValue,
          sign: data.sign
        },
        (ret, err) => {
          console.log(ret, err);
          if (ret.status) {
            this.isLoading = false;
            this.isPayLoading = false;
            this.$toast('支付成功');
            this.getList('order', false);
            // 支付成功
          } else {
            this.$toast('支付失败');
          }
        }
      );
    },
    countDownFinish() {
      this.getList('order', false);
    },
    orderTabchange(index) {
      this.orderTabWidth = this.$refs.orderTab[index].offsetWidth;
      this.orderTabLeft = this.$refs.orderTab[index].offsetLeft;
      localStorage.setItem('orderStatus', index);
      this.setStatus(index);
      this.getList('order', true);
    },
    setStatus(index) {
      console.log(index);
      // 待付款
      if (index) {
        // 待付款
        if (index === 1) {
          this.params.status = -2;
        }
        // 待收货
        if (index === 2) {
          this.params.status = 1;
          this.orderTabIndex = 1;
        }
        // 已完成
        if (index === 3) {
          this.params.status = 2;
        }
        // 已取消
        if (index === 4) {
          this.params.status = -1;
        }
      } else {
        delete this.params.status;
      }
      this.orderTabIndex = index;
    },
    copy(data) {
      this.$copyText(data).then(
        e => {
          this.$toast('复制成功');
        },
        e => {
          console.log(e);
        }
      );
    },
    // 确认收货
    confirmrRecv() {
      this.isLoading = true;
      this.$API.order
        .receive({
          id: this.orderId
        })
        .then(res => {
          if (!res.code) {
            this.isPopupShow = false;
            this.getList('order', true);
            this.$toast('确认成功');
            this.isPopupShow = false;
            this.isLoading = false;
          } else {
            this.$toast(res.message);
            this.isLoading = false;
          }
        });
    },
    goDetailsLink(id) {
      this.$router.push({ path: '/order/details', query: { id: id } });
    },
    // 取消订单
    cancelGoods(item) {
      this.$dialog
        .confirm({
          title: '温馨提醒',
          message: '确定取消该订单吗？',
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        })
        .then(() => {
          this.$API.order.cancel({ id: item.id }).then(res => {
            if (!res.code) {
              this.$toast('取消成功');
              this.getList('order', true);
            } else {
              this.$toast(res.message);
            }
          });
        });
    },
    // 再次支付订单
    payGoods(item) {
      this.isPopupPay = true;
      this.orderNo = item.order_no;
    },
    // 确认订单
    confirmGoods(data) {
      this.orderInfo = data;
      this.isPopupShow = true;
    },
    buyGoods(item) {
      this.$router.push({ path: '/store', query: { id: item.shop_id } });
    }
    // orderTab (type) {
    //   this.$router.push({ path: '/order/' + type, query: { isFromRoute: true } });
    // }
  }
};
</script>
<style lang="less" scoped>
.orderMall {
  display: flex;
  flex-direction: column;
  .content {
    overflow: auto;
    flex: 1;
  }
  .order-tab {
    display: flex;
    background-color: #fff;
    line-height: 88px;
    position: relative;
    .tab {
      display: block;
      flex: 1;
      text-align: center;
      .name {
        font-size: 28px;
        color: #666;
      }
    }
    .tab.active {
      .name {
        color: #ff0034;
        font-weight: 800;
      }
    }
    .activeLine {
      position: absolute;
      display: block;
      bottom: 15px;
      height: 4px;
      border-radius: 4px;
      transition: left ease 0.3s;
      background-color: #ff0034;
    }
  }
  .operation {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    font-size: 28px;
    color: #969aa6;
    padding: 15px 0px 20px;
    .text {
      color: #353535;
    }
    .confirm,
    .buy,
    .cancel,
    .pay {
      color: #fff;
      display: flex;
      justify-content: center;
      align-items: center;
      padding: 10px 20px;
      border-radius: 60px;
      margin-left: 15px;
      font-size: 28px;
    }
    .confirm {
      width: 216px;
    }
    .confirm,
    .pay {
      background-color: #ff0000;
      .time {
        color: #fff;
        margin-left: 5px;
      }
    }
    .pay {
      width: 216px;
      &::before {
        content: '';
        display: block;
        height: 30px;
        width: 30px;
        background-image: url('/static/img/icon-order-time.png');
        background-position: center center;
        background-repeat: no-repeat;
        background-size: 30px 30px;
        margin-right: 10px;
      }
    }
    .buy {
      color: #ff0000;
      border: 1px solid #ff0000; /*no*/
    }
    .cancel {
      color: #353535;
      border: 1px solid #999; /*no*/
    }
  }
  .confirm-goods {
    padding: 20px 40px 0;
    .title_name {
      font-size: 40px;
      color: #353535;
      padding: 15px 0 0;
      text-align: center;
    }
    .confirm_info {
      padding: 30px 0;
      color: #353535;
      font-size: 34px;
      text-align: center;
    }
    .tis {
      padding: 30px 0;
      color: #555;
      font-size: 24px;
    }
    .submit {
      display: flex;
      margin: 0 -40px;
      border-top: 1px solid #eee; /*no*/
      .btn {
        flex: 1;
        font-size: 34px;
        padding: 34px 0 31px;
        text-align: center;
      }
      .btn:first-child {
        border-right: 1px solid #eee; /*no*/
      }
      .cancel {
        color: #999;
      }
      .confirm {
        color: #ff0000;
      }
    }
  }
}
</style>
